package com.ibm.xhy.resources;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@RequestMapping("/api/user")
@RestController
public class UserResource{

    @Value("${jwt.secret}")
    private String secret;

    @RequestMapping("/{id}")
    public Object getInfo(@PathVariable String id) {
        Map<String, Object> result = new HashMap<>();
        result.put("id", id);
        result.put("name", secret);
//        List<Term> termList = StandardTokenizer.segment("攻城狮商品和服务");
//
//        result.put("hanlp", termList);
//
//        CustomDictionary.add("攻城狮");
//        List<Term> termList2 = StandardTokenizer.segment("攻城狮商品和服务");
//        result.put("hanlp2", termList2);
//
//        CustomDictionary.remove("攻城狮");
//        List<Term> termList3 = StandardTokenizer.segment("攻城狮商品和服务");
//        result.put("hanlp3", termList3);
        Map<String, Object> claims = new HashMap<>();
        claims.put("sub", "xxxx");
        result.put("token", this.generateToken(claims));

        return result;
    }

    @RequestMapping("/verify")
    public Object verifyToken(String token) {

        System.out.println(token);
        return this.getClaimsFromToken(token);

    }

    String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                //.setExpiration(generateExpirationDate())
                .signWith(SignatureAlgorithm.HS512, secret) //采用什么算法是可以自己选择的，不一定非要采用HS512
                .compact();
    }

    Claims getClaimsFromToken(String token) {
        Claims claims;
        try {

            claims = Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }
}


